import threading
import time
from queue import Queue
from pyevent.task import Task


class QThread(threading.Thread):
    """
    Thread with a queue.
    """

    def __init__(self, name=None, daemon=False):
        super().__init__()
        if name is not None:
            self.name = name
        else:
            pass  # let `name` inherits from Thread
        self.daemon = daemon
        self.queue = Queue()
        self._running = threading.Event()
        self._flag = threading.Event()  # 是否暂停
        self._flag.set()

    def __repr__(self):
        return '<QThread: {}, Class id: {}, Thread ident: {}>'.format(
            self.name,
            id(self),
            self.ident
        )

    def run(self):
        while self._running.isSet():
            self._flag.wait()
            try:
                if not self.queue.empty():
                    task = self.queue.get()
                    assert isinstance(task, Task)
                    if task.worker:
                        # print('thread name: ', self.name)
                        task.do()
                    self.queue.task_done()
                else:
                    time.sleep(0.01)  # 10ms
            except AssertionError as e:
                print('Thread queue item type error, Task type expected.')
            except Exception as e:
                raise e

    def start(self):
        self._running.set()
        self._flag.set()
        super().start()

    def pause(self):
        self._flag.clear()

    def resume(self):
        self._flag.set()

    def stop(self):
        self._running.clear()

    def put(self, task):
        self.queue.put(task)

    def put_nowait(self, task):
        self.queue.put_nowait(task)

    def get(self):
        return self.queue.get()

    def get_nowait(self):
        return self.queue.get_nowait()

    def qsize(self):
        return self.queue.qsize()

    def join(self):
        self.queue.join()
        super().join()